package com.sky.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    WeChatProperties weChatProperties;

    @Autowired
    UserMapper userMapper;

    private static final String WX_LOGIN_ADDR = "https://api.weixin.qq.com/sns/jscode2session";
    @Override
    public User wxLogin(UserLoginDTO loginDTO) {
        //只能获取到授权码
        String authCode = loginDTO.getCode(); // 唯一,一次性,5分钟
        //根据授权码获取唯一标识openId
        String openId = getOpenId(authCode);
        //如果openid有问题直接抛异常
        if (openId == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //业务分析
        //1.判断是不是第一次登陆 => 根据数据库查询 唯一标识id
        User user = userMapper.findUserByOpenId(openId);
        //2.第一次登陆 => 需要注册
        if(user == null){
            user = User.builder()
                    .openid(openId)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.save(user);
        }
        //3.后续登陆 => 直接返回
        return user;
    }

    /**
     * 根据授权码获取用户唯一标识(openid)
     * @param authCode
     * @return
     */
    private String getOpenId(String authCode)  {
        try {
            //使用HttpClient发送登陆请求
            // => 通过参数去微信拿openId
            HashMap<String, String> paramMap = new HashMap<>();
            paramMap.put("appid",weChatProperties.getAppid());
            paramMap.put("secret",weChatProperties.getSecret());
            paramMap.put("js_code",authCode);
            paramMap.put("grant_type","authorization_code");
            String jsonStr = HttpClientUtil.doGet(WX_LOGIN_ADDR,paramMap);
            ObjectMapper objectMapper = new ObjectMapper();
            Map map = objectMapper.readValue(jsonStr, Map.class);
            return (String) map.get("openid");
        } catch (JsonProcessingException ex) {
            //throw new RuntimeException(e);
            System.err.println(ex);
            return null;
        }
    }
}
